package com.itheima.controller;


import com.itheima.domain.Book;
import com.itheima.exception.BusinessException;
import com.itheima.exception.SystemException;
import com.itheima.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
// @RestController= @Controller + @ResponseBody
@RequestMapping("/books")
public class BookController {
    @Autowired
    private BookService bookService;
    // 查询全部
    @GetMapping
    public Result getAll(){
        List<Book> list = bookService.getAll();
        Result result = new Result(Code.GET_OK, list, "查询成功");
        return result;
    }

    // 通过ID查询   接收路径参数
    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id){
        if(id == 1){
            int i = 1/0;
        }else if(id == 2){
            throw new BusinessException(Code.BUSINESS_ERR1,"请不要用你的技术挑战我的耐心");
        }else if(id == 3){
            throw new SystemException(Code.SYSTEM_ERR,"网络堵塞，请稍后再试~");
        }
        Book book = bookService.getById(id);
        Result result = new Result(Code.GET_OK, book, "查询成功");
        return result;
    }

    // 新增  JSON参数
    @PostMapping
    public Result save(@RequestBody Book book){
        boolean flag = bookService.save(book);
        Result result = new Result(flag ? Code.SAVE_OK : Code.SAVE_ERR, null, flag?"添加成功":"添加失败");
        return result;
    }

    // 修改  JSON参数
    @PutMapping
    public Result update(@RequestBody Book book){
        boolean flag = bookService.update(book);
        Result result = new Result(flag ? Code.UPDATE_OK : Code.UPDATE_ERR, null, flag?"修改成功":"修改失败");
        return result;
    }
    // 删除  传参
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id){
        boolean flag = bookService.delete(id);
        Result result = new Result(flag ? Code.DELETE_OK : Code.DELETE_ERR, null, flag?"删除成功":"删除失败");
        return result;
    }

//    @RequestMapping("/model")
//    public ModelAndView modelAndView(ModelAndView mv){
//        mv.setViewName("/pages/books.html");
//        return mv;
//    }
}
